<?php

namespace app\home\controller;

use app\home\lib\MyController;
use app\home\lib\MyPhpExcel;
use think\Db;
use think\Request;

class Qa extends MyController
{
	// 处理excel文件进度
	public function excelRunProgress()
	{
		$excel_file = input('excel_file/s');
		$md5_excel_url = md5($excel_file);
		$rt = cache($md5_excel_url);
		if (empty($rt)) {
			return json(array('code' => '2', 'msg' => ""));
		} else {
			return $rt;
		}
	}

	// 导出问答记录
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/Qa/showRecordListDownload.html
	public function showRecordListDownload()
	{
		$create_date_from = session('recordList-create_date_from');
		$create_date_to = session('recordList-create_date_to');
		$page_one_time = date("Y-m-d", time());

		if (!empty($create_date_from) && empty($create_date_to)) {
			$between = $create_date_from . "to" . $page_one_time;
			// } else if (!empty($create_date_to) && !empty($create_date_from)) {
		} else {
			$between = $create_date_from . "to" . ($create_date_to > $page_one_time ? $page_one_time : $create_date_to);
		}

		// $excel_file = '回答记录_' . $between . '.xls';
		$excel_file = 'from' . $between . '.xls';

		$this->assign('excel_file', $excel_file);
		return $this->fetch();
	}

	// 导出问答记录
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/Qa/downloadRecordList.html
	public function downloadRecordList()
	{
		$excel_file = input('excel_file/s');
		$md5_excel_url = md5($excel_file);

		$url = (new MyPhpExcel())->getRecordListExcel($excel_file);
		cache($md5_excel_url, json_encode(['code' => 2, 'msg' => ""]), 60 * 10); //10*60秒过期

		return json(array('code' => '0', 'msg' => "EXCEL文件生成结束，请点击下方链接下载文件。", 'data' => ['url' => $url]));

		// $url = 'https://view.officeapps.live.com/op/view.aspx?src=' . urlencode($url . "?t=" . time());
		// header("Location: {$url}");
		// return;
	}

	// 问答记录
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/Qa/recordList.html
	public function recordList()
	{
		$page_one_time = trim(input('page_one_time/s', ''));
		$page = trim(input('page/s', 0));

		if (empty($page) || $page < 1) {
			$page = 1;
			$create_date_from = input('create_date_from/s', date('Y-m-d', strtotime("-1 day")));
			$create_date_to = input('create_date_to/s', '');
			$search = trim(input('search/s', ''));
			$page_one_time = date("Y-m-d H:i:s", time());

			session('recordList-create_date_from', $create_date_from ? $create_date_from : null);
			session('recordList-create_date_to', $create_date_to ? $create_date_to : null);
			session('recordList-search', $search ? $search : null);
			session('recordList-page_one_time', $page_one_time ? $page_one_time : null);
		} else {
			// 不是第一页
			$create_date_from = session('recordList-create_date_from');
			$create_date_to = session('recordList-create_date_to');
			$search = session('recordList-search');
			$page_one_time = session('recordList-page_one_time');
		}

		$where = [];
		if (!empty($create_date_from) && empty($create_date_to)) {
			$where['r.create_time'] = ['between', [$create_date_from . ' 00:00:00', $page_one_time]];
		} else if (!empty($create_date_to) && empty($create_date_from)) {
			$where['r.create_time'] = ['<=', $create_date_to . ' 23:59:59' > $page_one_time ? $page_one_time : $create_date_to . ' 23:59:59'];
		} else if (!empty($create_date_to) && !empty($create_date_from)) {
			$where['r.create_time'] = ['between', [$create_date_from . ' 00:00:00', $create_date_to . ' 23:59:59' > $page_one_time ? $page_one_time : $create_date_to . ' 23:59:59']];
		} else {
			$where['r.create_time'] = ['<', $page_one_time];
		}

		if (!empty($search)) {
			$where['u.nick_name'] = ['like', "%{$search}%"];
			// $where['r.nick_name'] = ['like', "%{$search}%"];
		}

		$userList = db("as_record")
			->field("r.openid,u.nick_name,max(r.create_time) end_time")
			->alias("r")
			->join("user_info u", "u.openid = r.openid")
			->where($where)
			->group('r.openid,u.nick_name')
			->cache(true, $this->cacheTime)
			->page($page, $this->onePage)
			->order('end_time desc')
			->select();

		// $userList = db("user_record_view")
		// 	->field("r.openid,r.nick_name,r.create_time end_time")
		// 	->alias("r")
		// 	->where($where)
		// 	->cache(true, $this->cacheTime)
		// 	->page($page, $this->onePage)
		// 	->order('r.create_time desc')
		// 	->select();
		// echo db("as_record")->getLastSql();
		$recordList = [];
		foreach ($userList as $key => $user) {
			$openid = $user['openid'];
			$record = [];
			// 1微信昵称
			if (!empty($user['nick_name'])) {
				$user['nick_name'] = iconv('UTF-8', 'GBK//IGNORE', $user['nick_name']);
				$user['nick_name'] = iconv('GBK', 'UTF-8//IGNORE', $user['nick_name']);
			} else {
				$user['nick_name'] = "微信用户";
			}
			$record['jbqk']['openid'] = $user['openid'];
			$record['jbqk']['end_time'] = $user['end_time'];
			$record['jbqk']['nick_name'] = $user['nick_name'];

			// 2取得答案
			$asList = db("as_record")
				->where('openid', $openid)
				->where('classify', '基本情况')
				->cache(true, $this->cacheTime)
				->select();
			foreach ($asList as $key => $as) {
				if ($as['classify'] == '基本情况') {
					$record['jbqk']["q_no_{$as['q_no']}"] = $as['my_answer'];
				} elseif ($as['classify'] == '闯关题') {
					$record['cgt']["q_no_{$as['q_no']}"] = ($as['is_right'] == 'yes' ? "[✓]" : "[×]") . "\r\n" . $as['my_answer'];
				} elseif ($as['classify'] == '科普题') {
					$record['kpt']["q_no_{$as['q_no']}"] = $as['my_answer'];
				}
			}
			$recordList[] = $record;
		}
		// var_dump($recordList);
		// die();

		$count = db("as_record")
			->field("r.openid,u.nick_name,max(r.create_time) end_time")
			->alias("r")
			->join("user_info u", "u.openid = r.openid")
			->where($where)
			->group('r.openid,u.nick_name')
			->cache(true, $this->cacheTime)
			->count();
		$allPage = ceil($count / $this->onePage);
		if ($page > $allPage) {
			$page = $allPage;
		}

		$this->assign('search', $search);
		$this->assign('page', $page);
		$this->assign('allPage', $allPage);
		$this->assign('create_date_from', $create_date_from);
		$this->assign('create_date_to', $create_date_to);
		$this->assign('count', $count);
		$this->assign('list', $recordList);
		return $this->fetch();
	}

	// 答题详情
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/Qa/recordDetail.html
	public function recordDetail()
	{
		$openid = input('openid/s');
		$record = [];
		// 1取得昵称
		$userInfo = db("user_info")->field("nick_name")->where("openid", $openid)->find();
		if (!empty($userInfo)) {
			$userInfo['nick_name'] = iconv('UTF-8', 'GBK//IGNORE', $userInfo['nick_name']);
			$userInfo['nick_name'] = iconv('GBK', 'UTF-8//IGNORE', $userInfo['nick_name']);
		} else {
			$userInfo['nick_name'] = "微信用户";
		}
		// $record['jbqk']['end_time'] = $user['end_time'];
		$record['jbqk']['nick_name'] = $userInfo['nick_name'];

		// 2取得答案
		$asList = db("as_record")
			->where('openid', $openid)
			->select();
		foreach ($asList as $key => $as) {
			$as['my_answer'] = str_replace(PHP_EOL, '<br>', $as['my_answer']);

			if ($as['classify'] == '基本情况') {
				$record['jbqk']["q_no_{$as['q_no']}"] = $as['my_answer'];
			} elseif ($as['classify'] == '闯关题') {
				$record['cgt']["q_no_{$as['q_no']}"] = '回答是否正确：' . ($as['is_right'] == 'yes' ? "[✓]" : "[×]") . "<br>" . $as['my_answer'];
			} elseif ($as['classify'] == '科普题') {
				$record['kpt']["q_no_{$as['q_no']}"] = $as['my_answer'];
			}
		}

		// var_dump($record);
		// die();

		$this->assign('record', $record);
		return $this->fetch();
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/qa/index.html
	public function index()
	{
		$page = input('page');
		$search = Request::instance()->post('search/a');

		if (!isset($page) || $page < 1) {
			$page = 1;
		}

		$limit = $this->onePage;

		$sqlWhere = '1=1';
		if (!empty($search['search_value'])) {
			$sqlWhere .= " AND q.title LIKE '%" . $search['search_value'] . "%'";
		} else {
			$search['search_value'] = '';
		}

		// 缓存问答编辑页面参数
		$qaIndexPageInfo = [];
		$qaIndexPageInfo['page'] = $page;
		$qaIndexPageInfo['search_value'] = $search['search_value'];
		cache(session_id() . "qaIndexPageInfo", $qaIndexPageInfo, 86400); //缓存 24 时(小时)=86400 秒

		$sqlCount = "SELECT COUNT(*) AS 'all' FROM `qa_main` as q WHERE " . $sqlWhere;
		$count = Db::query($sqlCount);
		$allPage = ceil($count[0]['all'] / $limit);
		if ($page > $allPage && $allPage > 0) {
			$page = $allPage;
		}
		$start = ($page - 1) * $limit;
		$sqlList = "SELECT q.* FROM `qa_main` as q WHERE  " . $sqlWhere . " ORDER BY id asc LIMIT $start,$limit";
		$qaList = Db::query($sqlList);

		foreach ($qaList as $key => $qa) {
			$where['qa_main_id'] = $qa['id'];
			// 取得题目数量
			$where = [];
			$where['qa_main_id'] = $qa['id'];
			$qa['qa_num'] = db('qa_bank')->where($where)->cache(true, $this->cacheTime)->count();

			$qaList[$key] = $qa;
		}

		$this->assign('page', $page);
		$this->assign('count', $count[0]['all']);
		$this->assign('allpage', $allPage);
		$this->assign('search', $search);
		$this->assign('qaList', $qaList);
		return $this->fetch();
	}

	// 编辑题目
	public function add()
	{
		$id = input('id');
		$page = input('page');
		$tab = input('tab');
		$selectedClassify = input('classify');
		$search = array(
			'search_value' => input('search_value'),
		);

		// 缓存问答编辑页面参数
		$qaMainPageInfo = [];
		$qaMainPageInfo['id'] = input('id');
		$qaMainPageInfo['page'] = input('page');
		$qaMainPageInfo['tab'] = input('tab');
		$qaMainPageInfo['search_value'] = input('search_value');
		cache(session_id() . "qaMainPageInfo", $qaMainPageInfo, 86400); //缓存 24 时(小时)=86400 秒

		if (!empty($id)) {
			$qaMain = db("qa_main q")
				->field("q.*")
				->where("q.id", $id)
				->find();
		} else {
			// 新建：默认值
			$qaMain = [];
			$qaMain['id'] = 0;
			$qaMain['status'] = 1;
		}

		$this->assign('page', $page);
		$this->assign('search', $search);
		$this->assign('tab', $tab);
		$this->assign('now_time', date("Y-m-d H:i:s", time()));
		$this->assign('qaMain', $qaMain);
		$this->assign('classify', $selectedClassify);
		return $this->fetch();
	}

	// 编辑 问答 基础信息
	public function edit()
	{
		$data = input('post.');
		$page = input('page');
		$search = array(
			'search_value' => input('search_value'),
		);

		if (empty($data['title'])) {
			$this->error('标题不能为空！');
		}

		if (empty($data['id'])) {
			if (empty($data['cover_image'])) {
				$data['cover_image'] = "https://uploads.jiankangpao.sichuancancer.org/uploads/images/20230206/a014a1cc2a77eb4b0f39e83aaf8b9074.jpg";
			}
			$res = db('qa_main')->insertGetId($data);
			$data['id'] = $res;
		} else {
			$res = db('qa_main')->where('id', $data['id'])->update($data);
		}

		$tiaozhuan = "id=" . $data['id'] . "&page=" . $page . "&tab=1&search_value=" . $search['search_value'];
		if ($res) {
			$this->redirect("add?" . $tiaozhuan);
		} else {
			$this->redirect("add?" . $tiaozhuan);
		}
	}

	// public function delete()
	// {
	// 	$id = input('id');
	// 	$page = input('page');
	// 	$status = input('status');
	// 	$search = array(
	// 		'search_value' => input('search_value'),
	// 	);

	// 	if (empty($id)) {
	// 		$this->error('数据为空！');
	// 	}

	// 	if ($status == 1) {
	// 		$status = 0;
	// 	} else {
	// 		$status = 1;
	// 	}
	// 	$res = db('qa_main')->where('id', $id)->update(array('status' => $status));
	// 	$tiaozhuan = "page=" . $page . "&search_value=" . $search['search_value'];
	// 	if ($res) {
	// 		$this->success('操作成功！', "index?" . $tiaozhuan);
	// 	} else {
	// 		$this->error('操作失败！', "index?" . $tiaozhuan);
	// 	}
	// }

	// // 删除分段问答结果
	// public function deleteResults()
	// {
	// 	$id = input('id');
	// 	$qaMainId = input('qaMainId');
	// 	db('qa_result_info')->where('id', $id)->where('qa_main_id', $qaMainId)->delete();
	// 	return json(array('code' => '0', 'msg' => "删除分段问答结果成功"));
	// }

	// // 根据分数段设置问答结果
	// public function setResults()
	// {
	// 	$qaMainId = input('qaMainId');
	// 	$classify = input('classify', '总分评估');

	// 	$data = input('post.');
	// 	$warnScore = $data['warn_score'];
	// 	$ratioScore = isset($data['ratio_score']) ? $data['ratio_score'] : '';
	// 	$standard = isset($data['standard']) ? $data['standard'] : '';
	// 	$evaluateMode = isset($data['evaluate_mode']) ? $data['evaluate_mode'] : '';
	// 	$percent_mode = isset($data['percent_mode']) ? $data['percent_mode'] : '';

	// 	if (isset($data['qa_result_json'])) {
	// 		$qaResultJson = $data['qa_result_json'];
	// 		foreach ($qaResultJson as $k => $v) {
	// 			$v['qa_main_id'] = $qaMainId;
	// 			$v['classify'] = $classify;
	// 			$v['ratio_score'] = $ratioScore;
	// 			$v['warn_score'] = $warnScore;
	// 			$v['standard'] = $standard;
	// 			$v['evaluate_mode'] = $evaluateMode;
	// 			$v['percent_mode'] = $percent_mode;
	// 			if (isset($v['id'])) {
	// 				$res = db('qa_result_info')->where('id', $v['id'])->update($v);
	// 			} else {
	// 				$res = db('qa_result_info')->insert($v);
	// 			}
	// 		}
	// 	}

	// 	$qaMainPageInfo = cache(session_id() . "qaMainPageInfo");
	// 	$tiaozhuan = "id=" . $qaMainPageInfo['id'] .
	// 		"&page=" . $qaMainPageInfo['page'] .
	// 		"&tab=2" .
	// 		"&search_value=" . $qaMainPageInfo['search_value'] .
	// 		"&classify=" . $classify;
	// 	$this->success('操作成功！', "Qa/add?" . $tiaozhuan);
	// }

	// // 设置问答结果-因子最高
	// public function setResultsYzzg()
	// {
	// 	$qaMainId = input('qaMainId');
	// 	$classify = input('classify');
	// 	$result_msg = input('result_msg'); //解读内容

	// 	if (empty($qaMainId) || empty($classify) || empty($result_msg)) {
	// 		$this->error('内容不能为空！');
	// 	}

	// 	// 删除原有设置
	// 	db('qa_result_info')->where('qa_main_id', $qaMainId)->where('classify', $classify)->delete();

	// 	$res = db('qa_result_info')->insert(['qa_main_id' => $qaMainId, 'classify' => $classify, 'result_msg' => $result_msg]);

	// 	$qaMainPageInfo = cache(session_id() . "qaMainPageInfo");
	// 	$tiaozhuan = "id=" . $qaMainPageInfo['id'] .
	// 		"&page=" . $qaMainPageInfo['page'] .
	// 		"&tab=2" .
	// 		"&search_value=" . $qaMainPageInfo['search_value'] .
	// 		"&classify=" . $classify;
	// 	$this->success('操作成功！', "Qa/add?" . $tiaozhuan);
	// }

	// // 设置问答结果-选项数量
	// public function setResultsXxsl()
	// {
	// 	$qaMainId = input('qaMainId');
	// 	$classify = input('classify');
	// 	$standard = input('standard'); //此项名称
	// 	$result_msg = input('result_msg'); //解读内容

	// 	if (empty($qaMainId) || empty($classify) || empty($standard) || empty($result_msg)) {
	// 		$this->error('内容不能为空！');
	// 	}

	// 	// 删除原有设置
	// 	db('qa_result_info')->where('qa_main_id', $qaMainId)->where('classify', $classify)->delete();

	// 	$res = db('qa_result_info')->insert(['qa_main_id' => $qaMainId, 'classify' => $classify, 'standard' => $standard, 'result_msg' => $result_msg]);

	// 	$qaMainPageInfo = cache(session_id() . "qaMainPageInfo");
	// 	$tiaozhuan = "id=" . $qaMainPageInfo['id'] .
	// 		"&page=" . $qaMainPageInfo['page'] .
	// 		"&tab=2" .
	// 		"&search_value=" . $qaMainPageInfo['search_value'] .
	// 		"&classify=" . $classify;
	// 	$this->success('操作成功！', "Qa/add?" . $tiaozhuan);
	// }
}
